<template>
    <fieldset>
        <legend>侦听器</legend>
        <input type="text" v-model='val'>
        <h1>{{ props.testVal }}</h1>
        <button>点击</button>
        <button @click="handleClick2">点击2</button>
    </fieldset>
</template>
<script setup>
import { watch, ref, defineProps, toRefs, nextTick, reactive } from "vue"
//watch

//侦听响应式变量
let val = ref("")

watch(val, (newVal, oldVal) => {
    console.log("new----", newVal);
    console.log("old----", oldVal);
})

//侦听props
let props = defineProps(['testVal', 'testVal2'])

// console.log(props);

//1..侦听整个props
// watch(props,(newVal,oldVal)=>{
//     console.log('newProps',newVal);
//     console.log('oldProps',oldVal);
// })

//2.侦听单个prop的变化
// watch( () => props.testVal,(newVal)=>{
//     console.log('newVal',newVal);
// })

//3.解构的props也可以侦听

// let {testVal2} = toRefs(props)

// watch(testVal2,(newVal)=>{
//     console.log('newTestVal2===',newVal);
// })


//4.侦听多个数据
// watch([()=>props.testVal,()=>props.testVal2],(newVal,oldVal)=>{
//     console.log('----',newVal);
//     console.log('--old--',oldVal);
// })

//5.强制触发侦听器
//侦听器函数执行优化，同时修改多次响应式，被watch同时侦听的时候，多次修改会合并成第一次watch回调来优化性能
// let msg1 = ref('')
// let msg2 = ref('小日子')

//可以通过下面这种手段强制触发侦听器函数进行多次回调
// let handleClick2 = async () => {
//     msg1.value = '德国',
//     await nextTick()
//     msg2.value = '日本'
// }


// watch([msg1, msg2], (newVal) => {
//     console.log(newVal);
// })

//6.侦听对象/对象属性

let obj = reactive({
    name: "李雷",
    age: 20,
    parson: {
        nickname: "卢本伟"
    }
})

setTimeout(() => {
    obj.name = '韩梅梅',
        obj.person.nickname = '55开'
}, 2000)
//侦听属性
// watch(() => obj.name, (newVal) => {
//     console.log(newVal);
// })

//深度侦听/立即执行watch
watch(() => obj.parson.nickname, (newVal) => {
    console.log(newVal);
},{
    deep:true,
    immediate:true
})
</script>